package ao

import (
    "github.com/mojocn/base64Captcha"
    log "github.com/sirupsen/logrus"
    "image/color"
)

type CaptchaParams struct {
    CaptchaType string
    Height      uint64
    Width       uint64
}

var store = base64Captcha.DefaultMemStore

// 生成Captcha
func GenerateCaptcha(params CaptchaParams) (string, string, error) {
    var captchaID, captchaCode string

    var driver base64Captcha.Driver

    switch params.CaptchaType {
    case "audio":
        driver = base64Captcha.NewDriverAudio(6, "zh")
    case "math":
        driver = base64Captcha.NewDriverMath(
            int(params.Height),
            int(params.Width),
            0,
            base64Captcha.OptionShowHollowLine,
            // https://captcha.mojotv.cn/
            &color.RGBA{
                R: 83,
                G: 237,
                B: 125,
                A: 64,
            },
            []string{"wqy-microhei.ttc"},
        )
    case "string":
        driver = base64Captcha.NewDriverString(
            int(params.Height),
            int(params.Width),
            0,
            base64Captcha.OptionShowHollowLine,
            4,
            "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
            // https://captcha.mojotv.cn/
            &color.RGBA{
                R: 83,
                G: 237,
                B: 125,
                A: 64,
            },
            []string{"wqy-microhei.ttc"},
        )

    default:
        driver = base64Captcha.NewDriverDigit(
            int(params.Height),
            int(params.Width),
            5,
            0.7,
            80,
        )
    }

    c := base64Captcha.NewCaptcha(driver, store)
    captchaID, captchaCode, err := c.Generate()
    if err != nil {
        log.Errorf("generate code error:%+v", err)
        return "", "", err
    }

    return captchaID, captchaCode, nil
}

func VerifyCaptcha(captchaID, captchaCode string) bool {
    return store.Verify(captchaID, captchaCode, true)
}
